import { getUsers, saveUsers } from "../../server-data/users";

export default defineEventHandler(async (event) => {
  const { id } = event.context.params;
  const method = event.method;

  // 获取所有的用户
  const users = await getUsers();

  if (method === "GET") {
    // 根据 id 获取用户数据
    const user = users.find((u) => u.id === id);
    if (!user) {
      event.node.res.statusCode = 404;
      return { error: "没有找到对应id的用户" };
    }
    return user;
  }

  if (method === "PATCH") {
    // 根据 id 更新用户数据
    const body = await readBody(event);
    const index = users.findIndex((u) => u.id === id);
    if (index === -1) {
      event.node.res.statusCode = 404;
      return { error: "没有找到对应id的用户" };
    }

    users[index] = { ...users[index], ...body };
    await saveUsers(users);
    return users[index];
  }

  if (method === "DELETE") {
    // 根据 id 删除用户数据
    const index = users.findIndex((u) => u.id === id);
    if (index === -1) {
      event.node.res.statusCode = 404;
      return { error: "没有找到对应id的用户" };
    }
    users.splice(index, 1);
    await saveUsers(users);
    return { success: true };
  }

  event.node.res.statusCode = 405;
  return { error: "不支持的方法" };
});
